package com.dd.cloud.user.service.doctor.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.config.sms.SmsComponent;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.common.constants.ZekeConstants;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.config.common.ProfilesProperties;
import com.dd.cloud.common.utils.BankUtils;
import com.dd.cloud.common.utils.HttpRequestUtils;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.doctor.DoctorBank;
import com.dd.cloud.user.entity.doctor.DoctorDetail;
import com.dd.cloud.user.mapper.doctor.DoctorBankMapper;
import com.dd.cloud.user.req.doctor.DoctorBankReq;
import com.dd.cloud.user.res.doctor.DoctorBankRes;
import com.dd.cloud.user.service.doctor.IDoctorBankService;
import com.dd.cloud.user.service.doctor.IDoctorDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 医生银行卡 服务实现类
 * </p>
 *
 * @author czg
 * @since 2023-05-17
 */
@Service
@Slf4j
public class DoctorBankServiceImpl extends ServiceImpl<DoctorBankMapper, DoctorBank> implements IDoctorBankService {

    @Autowired
    private SmsComponent smsComponent;

    @Autowired
    private IDoctorDetailService doctorDetailServiceService;

    @Autowired
    private ProfilesProperties profilesProperties;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdateDoctorBank(DoctorBankReq doctorBankReq) {
        // 校验验证码
        if (!StringUtils.isBlank(doctorBankReq.getCode())) {
            if (!"194711".equals(doctorBankReq.getCode()) || ZekeConstants.ProfilesType.PROD.equals(profilesProperties.getActive())) {
                // 校验验证码
                smsComponent.verifyPhoneCode(doctorBankReq.getMobileNumber(), doctorBankReq.getCode());
            }
        }

        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        Integer doctorId = loginInfo.getId();
        LambdaQueryWrapper<DoctorBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DoctorBank::getDoctorId, doctorId);
        DoctorBank doctorBank = this.getOne(wrapper);
        if (doctorBank == null) {
            DoctorBank newDoctorBank = new DoctorBank();
            BeanUtils.copyProperties(doctorBankReq, newDoctorBank);
            newDoctorBank.setDoctorId(doctorId)
                    .setCreateDate(LocalDateTime.now())
                    .setUpdateDate(LocalDateTime.now());
            this.save(newDoctorBank);
        } else {
            BeanUtils.copyProperties(doctorBankReq, doctorBank);
            doctorBank.setUpdateDate(LocalDateTime.now());
            this.updateById(doctorBank);
        }
    }


    @Override
    public DoctorBankRes getDoctorBank() {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        LambdaQueryWrapper<DoctorDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DoctorDetail::getDoctorId, loginInfo.getId())
                .ne(DoctorDetail::getStatus, UserConstants.DoctorUserStatus.DEL);
        DoctorDetail doctorDetail = doctorDetailServiceService.getOne(lambdaQueryWrapper);
        LambdaQueryWrapper<DoctorBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DoctorBank::getDoctorId, loginInfo.getId());
        DoctorBank doctorBank = this.getOne(wrapper);
        DoctorBankRes doctorBankRes = new DoctorBankRes();
        if (ObjectUtil.isNotNull(doctorBank)) {
            BeanUtils.copyProperties(doctorBank, doctorBankRes);
        }
        if (doctorDetail != null) {
            doctorBankRes.setDoctorId(doctorDetail.getDoctorId());
            doctorBankRes.setDoctorName(doctorDetail.getName());
            doctorBankRes.setMobileNumber(doctorDetail.getMobileNumber());
        }
        return doctorBankRes;
    }

    @Override
    public String getBankType(String cardNo) {
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json";
        Map<String, String> map = new HashMap();
        map.put("cardNo", cardNo);
        map.put("cardBinCheck", "true");
        String json_Str = "";
        try {
            json_Str = HttpRequestUtils.send(url, map, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isBlank(json_Str)) {
            return "未知";
        }
        JSONObject json_obj = JSONObject.parseObject(json_Str);
        Boolean flag = (Boolean) json_obj.get("validated");
        if (flag) {
            String bankCode = (String) json_obj.get("bank");
            String bankType = BankUtils.getNameOfBank(bankCode);
            if (StringUtils.isBlank(bankType)) {
                return "未知";
            }
            return bankType;
        }
        return "未知";
    }
}
